import { message } from 'ant-design-vue'

/**
 * 语音服务模块
 * 负责处理文字转语音相关的API调用
 */
export const voiceService = {
  /**
   * 文字转语音API调用
   * @param {string} text - 要转换的文本
   * @param {string} voiceType - 音色类型
   * @returns {Promise<{audioUrl: string}>} 返回音频URL
   */
  async textToSpeech(text, voiceType = 'male', onEnd = null) {
    try {
      // 优先使用Web Speech API进行真实语音合成
      if ('speechSynthesis' in window) {
        return await this.generateSpeechWithWebAPI(text, voiceType, onEnd);
      }
      
      // 如果不支持Web Speech API，则使用模拟音频
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 实际项目中这里应该调用真实的TTS API
      // 例如：
      // const response = await fetch('/api/tts', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ text, voiceType })
      // })
      // return await response.json()
      
      // 生成基于文本的模拟音频URL
      const testAudioUrls = [
        'https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3',
        'https://file-examples.com/storage/fe68c8777d66f45d2b1c1a9/2017/11/file_example_MP3_700KB.mp3',
        'https://sample-videos.com/zip/10/mp3/mp3-15s.mp3'
      ];
      
      // 根据文本长度选择不同的测试音频
      const audioIndex = text.length % testAudioUrls.length;
      
      return {
        success: true,
        audioUrl: testAudioUrls[audioIndex],
        duration: Math.max(10, Math.min(60, text.length / 10)) // 根据文本长度估算时长
      }
    } catch (error) {
      console.error('文字转语音API调用失败:', error)
      throw new Error('语音生成失败，请重试')
    }
  },

  /**
   * 使用Web Speech API生成语音
   * @param {string} text - 要转换的文本
   * @param {string} voiceType - 音色类型
   * @param {Function} onEnd - 播放结束回调
   * @returns {Promise<{audioUrl: string}>} 返回音频URL
   */
  async generateSpeechWithWebAPI(text, voiceType = 'male', onEnd = null) {
    return new Promise((resolve, reject) => {
      try {
        const utterance = new SpeechSynthesisUtterance(text);
        
        // 设置语音参数
        utterance.rate = 0.8; // 语速
        utterance.pitch = voiceType === 'female' ? 1.2 : 0.8; // 音调
        utterance.volume = 1; // 音量
        utterance.lang = 'zh-CN'; // 中文
        
        // 尝试选择合适的声音
        const voices = speechSynthesis.getVoices();
        console.log('可用语音列表:', voices.map(v => ({ name: v.name, lang: v.lang })));
        
        const chineseVoices = voices.filter(voice => 
          voice.lang.includes('zh') || voice.lang.includes('CN') || voice.lang.includes('Chinese')
        );
        
        if (chineseVoices.length > 0) {
          let targetVoice;
          
          if (voiceType === 'female') {
            // 优先查找女声
            targetVoice = chineseVoices.find(voice => 
              voice.name.toLowerCase().includes('female') || 
              voice.name.includes('女') ||
              voice.name.toLowerCase().includes('woman') ||
              voice.name.toLowerCase().includes('xiaoxiao') ||
              voice.name.toLowerCase().includes('xiaoyi')
            );
          } else {
            // 优先查找男声
            targetVoice = chineseVoices.find(voice => 
              voice.name.toLowerCase().includes('male') || 
              voice.name.includes('男') ||
              voice.name.toLowerCase().includes('man') ||
              voice.name.toLowerCase().includes('yunyang') ||
              voice.name.toLowerCase().includes('kangkang')
            );
          }
          
          // 如果没找到特定性别的声音，使用第一个中文声音
          utterance.voice = targetVoice || chineseVoices[0];
          console.log('选择的语音:', utterance.voice?.name, '音色类型:', voiceType);
        }
        
        utterance.onstart = () => {
          console.log('语音开始播放');
        };
        
        utterance.onend = () => {
          console.log('语音播放结束');
          if (onEnd && typeof onEnd === 'function') {
            onEnd();
          }
        };
        
        utterance.onerror = (error) => {
          console.error('语音合成错误:', error);
          reject(new Error('语音合成失败'));
        };
        
        // 开始语音合成
        speechSynthesis.speak(utterance);
        
        // 立即返回结果，不等待播放结束
        resolve({
          success: true,
          audioUrl: 'web-speech-api', // 特殊标识，表示使用Web Speech API
          duration: Math.max(3, text.length / 5), // 估算时长，最少3秒
          utterance: utterance // 返回utterance对象以便外部控制
        });
        
      } catch (error) {
        reject(error);
      }
    });
  },

  /**
   * 验证音频URL是否有效
   * @param {string} url - 音频URL
   * @returns {Promise<boolean>} 是否有效
   */
  async validateAudioUrl(url) {
    return new Promise((resolve) => {
      const audio = new Audio()
      audio.oncanplaythrough = () => resolve(true)
      audio.onerror = () => resolve(false)
      audio.src = url
    })
  },

  /**
   * 下载音频文件
   * @param {string} audioUrl - 音频URL
   * @param {string} filename - 文件名
   */
  async downloadAudio(audioUrl, filename = 'voice.wav') {
    try {
      const response = await fetch(audioUrl)
      const blob = await response.blob()
      
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      message.success('音频下载成功')
    } catch (error) {
      console.error('音频下载失败:', error)
      message.error('音频下载失败，请重试')
    }
  }
}